package com.itcm.skymail.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.itcm.common.to.es.SkuEsModel;
import com.itcm.skymail.search.config.SkymailElasticSearchConfig;
import com.itcm.skymail.search.constant.EsConstant;
import com.itcm.skymail.search.service.MallSearchService;
import com.itcm.skymail.search.vo.SearchParam;
import com.itcm.skymail.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述:
 *
 * @author cm_fighting
 * @create 2020-10-21 4:21 下午
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Resource
    private RestHighLevelClient client;


    @Override
    public SearchResult search(SearchParam param) {
        // 1. 创建并构建检索请求
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            SearchResponse searchResponse = client.search(searchRequest, SkymailElasticSearchConfig.COMMON_OPTIONS);
            return buildSearchResult(searchResponse, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 创建并构建检索请求 ：
     * 包括模糊匹配 ，过滤（按照属性、分类、品牌、价格区间，库存），排序，分页，高亮，聚合分析
     *
     * @return searchRequest
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        // 创建searchSourceBuilder，用来构建DSL语句
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        /*
         * 复合查询 bool
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1. must  按名字模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // 2. filter
        // 2.1 catalog3Id 按照三级分类id过滤
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // 2.2 brandId 按照品牌id过滤
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // attrs todo 2.3 按照属性过滤
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            for (String attr : param.getAttrs()) {
                // attr 格式为 1_4寸:5.5寸
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        // 2.4 hasStock 按照是否有库存过滤
        boolQuery.filter(QueryBuilders.termsQuery("hasStock", param.getHasStock() == 1));

        // 2.5 按照价格区间过滤
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            // 传参格式 1_500 、 _500 、 500_ 三种情况
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] arr = param.getSkuPrice().split("_");
            if (arr.length == 2) {
                rangeQuery.gte(arr[0]).lte(arr[1]);
            } else if (arr.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(arr[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(arr[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        searchSourceBuilder.query(boolQuery);

        /*
         * 排序 分页 高亮
         */
        // 1. 排序
        if (!StringUtils.isEmpty(param.getSort())) {
            // sort 格式 hotScore_asc
            String sort = param.getSort();
            String[] s = sort.split("_");
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(s[0], sortOrder);
        }
        // 2. 分页
        searchSourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        // 3. 高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            // 高亮为搜索词高亮显示，所以必须有关键词是才高亮处理
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        /*
         * 聚合分析
         */
        // 1. 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        // 品牌聚合的子聚合 -- brand_name_agg 、brand_img_agg
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);

        // 2. 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        // 分类聚合的子聚合 -- catalog_name_agg
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);

        // 3. 属性聚合 嵌入式的 nested
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(attr_agg);

        System.out.println("构建的DSL " + searchSourceBuilder.toString());
        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
    }

    // 根据es返回结果SearchResponse构建SearchResult
    private SearchResult buildSearchResult(SearchResponse searchResponse, SearchParam param) {
        System.out.println(searchResponse);
        SearchHits hits = searchResponse.getHits();
        SearchResult result = new SearchResult();

        // 查询到的所有商品
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                // _source 才是原数据 getSourceAsString获取的正是json格式字符串
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                // 将标题替换为高亮的标题
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                esModels.add(skuEsModel);
            }
        }
        result.setProducts(esModels);

        /*
         * 分析返回的聚合信息
         */
        // 1. 返回商品涉及到的所有分类
        ParsedLongTerms catalog_agg = searchResponse.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 当前聚合获取分类ID
            Long keyAsString = Long.valueOf(bucket.getKeyAsString());
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(keyAsString);
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            // 子聚合中获取分类名
            String catalogName = catalog_name_agg.getBuckets().get(0).getKey().toString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        // 2.  返回商品涉及到的所有品牌
        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brandBuckets = brand_agg.getBuckets();
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brandBuckets) {
            // 当前聚合获取品牌ID
            Long keyAsString = Long.valueOf(bucket.getKeyAsString());
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            brandVo.setBrandId(keyAsString);

            // 子聚合中获取品牌名
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKey().toString();
            brandVo.setBrandName(brandName);

            // 子聚合中获取品牌img
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKey().toString();
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);

        }
        result.setBrands(brandVos);
        System.out.println(brandVos.toString());

        // 返回商品涉及到的所有属性 - 嵌入式的
        ParsedNested attr_agg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrBuckets = attr_id_agg.getBuckets();
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : attrBuckets) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();

            String keyAsString = bucket.getKeyAsString();
            long attrId = Long.parseLong(keyAsString);
            attrVo.setAttrId(attrId);

            // 子聚合中获取属性名
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKey().toString();
            attrVo.setAttrName(attrName);

            // 子聚合中获取属性值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attr_value_agg.getBuckets().stream().map(item -> {
                return item.getKeyAsString();
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        /*
         * 分页信息
         */
        // 当前页面
        result.setPageNum(param.getPageNum());
        // 总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        // 总页码
        int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : (int) (total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(totalPages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        return result;
    }
}
